package com.bltec.emergency.controller.mgrController;

import com.bltec.emergency.common.ResponseJson;
import com.bltec.emergency.model.LogInfo;
import com.bltec.emergency.model.User;
import com.bltec.emergency.service.mgrService.LogInfoService;
import com.bltec.emergency.service.commonService.LoginService;
import com.bltec.emergency.utils.DateUtil;
import com.bltec.emergency.utils.WebUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.ParseException;

@RestController
public class LoginController {
    //与登录service层进行交互
    @Resource
    private  LoginService loginService;
    //登录记录service
    @Resource
    private LogInfoService logInfoService;

    @RequestMapping(method = RequestMethod.POST,value = "/login")
    public ResponseJson login(String userName, String passWord, HttpSession session) {
        if(userName!=null&&passWord!=null&&loginService.hasUser(userName)) {
            User user = loginService.getByUserName(userName);
            if(!user.getEnable()){return ResponseJson.LOGIN_FAIL_LOCK;}
            if(user.getPassword().equals(passWord)){
                //使用SecurityUtils创建一个当前的用户
                Subject subject = SecurityUtils.getSubject();
                //使用用户的关键信息创建一个token令牌用于验证
                UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);

                // 执行认证登陆,这里会调用MyRealm中的doGetAuthenticationInfo方法进行身份验证
                subject.login(token);
                try {
                    //登陆成功后，将登录信息录入logInfo表中
                    LogInfo log = new LogInfo();
                    log.setIpAddress(WebUtils.getRequest().getRemoteAddr());
                    log.setUserId(user.getId());
                    log.setLoginTime(DateUtil.dateNow());
                    logInfoService.save(log);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                session.setAttribute("user",user.getUsername());
                session.setAttribute("ip",WebUtils.getRequest().getRemoteAddr());
//                System.err.println(token);
                return ResponseJson.LOGIN_SUCCESS;
            }else {
                return ResponseJson.LOGIN_FAIL_PWD;
            }
        }else {
            return ResponseJson.LOGIN_FAIL_USER_NO_FOUND;
        }
    }
}
